package com.scalar.chiptrack.adaptor.ibm;

import com.scalar.ScalarException;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.chiptrack.users.VendorAdaptor;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import HTTPClient.HTTPConnection;
import HTTPClient.HTTPResponse;
import HTTPClient.CookieModule;
import HTTPClient.NVPair;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 20 Nov, 2009
 * Time: 10:30:34 AM
 */
public class IBMAdaptor extends JobHandler implements AdaptorConstants
{

    private static final String PROTOCOL_SCHEME_HTTPS = "https";
    private static final int DEFAULT_SSL_PORT = 443;
    private static final String HOST = "www-309.ibm.com";
    private static final String LOGIN_INDEX = "/technologyconnect/index.jsp";
    private static final String LOGIN_INDEX1 = "/technologyconnect/login.jsp";
    private static final String POST_URI_LOGIN = "/technologyconnect/IRServlet.wss";
    private static final String POST_URI_LOGIN1 = "/technologyconnect/j_security_check";
    private static final String GET_URI_LOGOUT = "/technologyconnect/ibm_security_logout?logoutExitPage=/index.jsp&amp;logout=Logout";
    private static final String WIP_TRACKING_LINK = "/technologyconnect/orst/ORSTServlet.wss?linkid=150000&FUNC=WIP";

    private static final String WIP_DOWNLOAD = "/technologyconnect/orst/ORSTServlet.wss";
    private static final String SHIP_DOWNLOAD = "/technologyconnect/ordmgt/Download.wss";

    private static final String GET_WIP_REPORT
            = "/technologyconnect/orst/ORSTServlet.wss?skip=N&linkid=152000&opn=rep&reptype=XXXXX&id=REPWIPT01&pghead=WIP+report&subhead=Main+WIP+tracking+report%2C+with+extensive+query+customization+capabilities";
    private static final String SHIPMENT_STATUS_LINK = "/technologyconnect/ordmgt/shipstat.wss?linkid=134000&oper=STATUS";

    private static final String REDIRECT_SIGNIN_PAGE = "/technologyconnect/signin.jsp";


    public static final String FILE_NAME_WIP_STATUS     = "IBM_WIP_TRACKING";
    public static final String FILE_NAME_SHIP_STATUS    = "SHIPPING_INFO_REPORT";

    public static final String ADAPTOR_NAME = "IBM_FAB";

    private String m_dataOutputDir  = null;
    private Logger m_adaptorLogger  = null;
    private String m_username       = null;
    private String m_password       = null;
    private String m_accountNumber  = null;
    private int    m_adaptor_id     = -1;

    public IBMAdaptor() throws ScalarException
    {
        try
        {

            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation( VENDOR_NAME_IBM, LOCATION_TYPE_FAB );

            m_username = vendorAdaptor.getUserId().trim();
            m_password = vendorAdaptor.getPassWord().trim();
            m_accountNumber = vendorAdaptor.getCustomerId().trim();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory().trim();

            if ( m_dataOutputDir != null )
            {
                if ( m_dataOutputDir.endsWith( "/" ) || m_dataOutputDir.endsWith( "\\" ) )
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }
            }

            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );

            m_adaptorLogger = AdaptorUtils.getAdaptorLogger( m_dataOutputDir , VENDOR_NAME_IBM);
            AdaptorUtils.setLogger( m_adaptorLogger );

        }
        catch ( ScalarException se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading IBM Adaptor Username, Password details from database, Exception: " + se );
            throw se;
        }

    }

    public static void main( String[] args ) throws Exception
    {
        new IBMAdaptor().execute();
    }

    public void execute() throws Exception
    {
        try
        {
            m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);

            AdaptorUtils.printHeader(VENDOR_NAME_IBM, CONSTANT_ADAPTOR );

            AdaptorUtils.removeOldFiles(m_dataOutputDir, m_adaptorLogger);

            HTTPConnection connection = login( HOST, DEFAULT_SSL_PORT, m_username, m_password );

            if ( connection != null )
            {

                HTTPResponse rsp = requestWipTrackingReport( connection );
                BufferedReader reader = null;
                if ( rsp != null )
                {
                    System.out.println( "Trying to download WIP TRACKING REPORT " );
                    log( "Trying to download WIP TRACKING REPORT " );

                    reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
                    AdaptorUtils.saveAsFile( reader, m_dataOutputDir, FILE_NAME_WIP_STATUS , FILE_EXTN_CSV );
                    if ( m_adaptor_id > 0 )
                    {
                        AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_WIP_STATUS, FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                    }
                    System.out.println( "Downloading WIP_TRACKINGP is compeleted" );
                    log( "Downloading WIP_TRACKINGP is compeleted" );
                }
     
                //Dowmloading ShipmentFile Starts

                rsp = requestShipmentStatus( connection );
                if ( rsp != null )
                {
                    reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );

                    System.out.println( "Trying to download SHIPMENT STATUS" );
                    log( "Trying to download SHIPMENT STATUS" );

                    AdaptorUtils.saveAsFile( reader, m_dataOutputDir, FILE_NAME_SHIP_STATUS , FILE_EXTN_CSV );
                    if ( m_adaptor_id > 0 )
                    {
                        AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_SHIP_STATUS, FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                    }

                    System.out.println( "Downloading SHIPMENT STATUS is compeleted" );
                    log( "Downloading SHIPMENT STATUS is compeleted" );

                }
                logout( connection );
            }
            else
            {

            }
        }
        catch ( Exception e )
        {
            AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger);
            AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id );
            System.out.println("Exception while trying to connect and read data from "+HOST +" site: " + e);
            e.printStackTrace();
            throw e;
        }
    }

    // changed by hareesh on 1st March 2004
    private HTTPConnection login( String host, int port, String username, String password ) throws Exception
    {
        String line = null;

        HTTPConnection conn = new HTTPConnection( PROTOCOL_SCHEME_HTTPS, host, port );
        CookieModule.setCookiePolicyHandler( null );
        conn.addDefaultModule( CookieModule.class, -1 );

        NVPair defaultHeaders[] = new NVPair[ 9 ];
        defaultHeaders[ 0 ] = new NVPair( "Accept", "*/*" );
        defaultHeaders[ 1 ] = new NVPair( "Referer", "http://" + host );
        defaultHeaders[ 2 ] = new NVPair( "Accept-Language", "en-us" );
        defaultHeaders[ 3 ] = new NVPair( "Content-Type", "application/x-www-form-urlencoded" );
        defaultHeaders[ 4 ] = new NVPair( "Proxy-Connection", "Keep-Alive" );
        defaultHeaders[ 5 ] = new NVPair( "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)" );
        defaultHeaders[ 6 ] = new NVPair( "Host", host );
        defaultHeaders[ 8 ] = new NVPair( "Pragma", "no-cache" );

        conn.setDefaultHeaders( defaultHeaders );

        log( "\nTrying to log in... " );
        System.out.println( "\nTrying to log in... " );

        HTTPResponse rsp = conn.Post( POST_URI_LOGIN );

        /*BufferedReader reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );

        while ( ( line = reader.readLine() ) != null )
        {
            //System.out.println(line);
            //log(line);
        }*/

        NVPair[] formData = new NVPair[ 2 ];
        
        formData[ 0 ] = new NVPair( "j_username", username );
        formData[ 1 ] = new NVPair( "j_password", password );

        rsp = conn.Post( POST_URI_LOGIN1, formData );

        if ( rsp.getEffectiveURI().toString().endsWith( REDIRECT_SIGNIN_PAGE ) )
        {

            throw new ScalarException( "********ERROR!! ERROR!! ERROR!! InValid UserName and Password********** n n " );
        }

        /*BufferedReader reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
        line = null;
        while ( ( line = reader.readLine() ) != null )
        {
            //System.out.println(line);
            log(line);
        }*/
        log( "successfully logged in\n" );
        System.out.println( "successfully logged in\n" );
        return conn;

    }

    private HTTPResponse requestWipTrackingReport( HTTPConnection conn ) throws Exception
    {

        System.out.println( "Submitting HTTP Request for Wip Tracking .... " );
        log( "Submitting HTTP Request for Wip Tracking ..... " );

        HTTPResponse rsp = conn.Get( GET_WIP_REPORT );
       /* BufferedReader reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
        String line = null;
        while ( ( line = reader.readLine() ) != null )
        {
            log(line);
        }*/

        NVPair[] formData = new NVPair[ 79 ];

        formData[ 0 ] = new NVPair( "showfilter", "" );
        formData[ 1 ] = new NVPair( "vendor_id",  m_accountNumber );
        formData[ 2 ] = new NVPair( "bucket_name", "'DESC1'" );
        formData[ 3 ] = new NVPair( "product_name_Src", "'ALL'" );
        formData[ 4 ] = new NVPair( "product_name", "" );
        formData[ 5 ] = new NVPair( "cpd", "" );
        formData[ 6 ] = new NVPair( "future1", "'ALL'" );
        formData[ 7 ] = new NVPair( "lot_id", "" );

        formData[ 8 ] = new NVPair( "stage_category", "'ALL'" );
        formData[ 9 ] = new NVPair( "facility", "'ALL'" );
        formData[ 10 ] = new NVPair( "poid", "" );
        formData[ 11 ] = new NVPair( "detail_storage", "" );
        formData[ 12 ] = new NVPair( "mDATE1", "" );
        formData[ 13 ] = new NVPair( "dDATE1", "" );
        formData[ 14 ] = new NVPair( "yDATE1", "" );
        formData[ 15 ] = new NVPair( "pcd", "ALL" );

        formData[ 16 ] = new NVPair( "mDATE2", "" );
        formData[ 17 ] = new NVPair( "dDATE2", "" );
        formData[ 18 ] = new NVPair( "yDATE2", "" );
        

        formData[ 19 ] = new NVPair( "opn_alt", "" );
        formData[ 20 ] = new NVPair( "First", "Y" );
        formData[ 21 ] = new NVPair( "sortF", "1" );
        formData[ 22 ] = new NVPair( "sortO", "ASC" );
        formData[ 23 ] = new NVPair( "skip", "N" );
        formData[ 24 ] = new NVPair( "nof", "30" );
        formData[ 25 ] = new NVPair( "sr", "Y" );
        formData[ 26 ] = new NVPair( "id", "REPWIPT01" );
        formData[ 27 ] = new NVPair( "text", "Y" );
        formData[ 28 ] = new NVPair( "reptype", "XXXXX" );

        formData[ 29 ] = new NVPair( "linkid", "152000" );
        formData[ 30 ] = new NVPair( "FUNC", "WIP" );
        formData[ 31 ] = new NVPair( "download", "Y" );
        formData[ 32 ] = new NVPair( "pghead", "WIP report" );
        formData[ 33 ] = new NVPair( "subhead", "Main WIP tracking report, with extensive query customization capabilities" );
        formData[ 34 ] = new NVPair( "nextstart", "1" );
        
        formData[ 35 ] = new NVPair( "showsumREPWIPT01", "ALL" );

        formData[ 36 ] = new NVPair( "rep_breakREPWIPT01", "None" );

        formData[ 37 ] = new NVPair( "colsREPWIPT011", "Y" );
        formData[ 38 ] = new NVPair( "colsREPWIPT012", "Y" );
        formData[ 39 ] = new NVPair( "colsREPWIPT013", "Y" );
        formData[ 40 ] = new NVPair( "colsREPWIPT014", "Y" );
        formData[ 41 ] = new NVPair( "colsREPWIPT015", "Y" );
        formData[ 42 ] = new NVPair( "colsREPWIPT016", "Y" );
        formData[ 43 ] = new NVPair( "colsREPWIPT017", "Y" );
        formData[ 44 ] = new NVPair( "colsREPWIPT018", "Y" );
        formData[ 45 ] = new NVPair( "colsREPWIPT019", "Y" );
        formData[ 46 ] = new NVPair( "colsREPWIPT0110", "Y" );
        formData[ 47 ] = new NVPair( "colsREPWIPT0111", "Y" );
        formData[ 48 ] = new NVPair( "colsREPWIPT0112", "Y" );
        formData[ 49 ] = new NVPair( "colsREPWIPT0114", "Y" );
        formData[ 50 ] = new NVPair( "colsREPWIPT0115", "Y" );
        formData[ 51 ] = new NVPair( "colsREPWIPT0116", "Y" );
        formData[ 52 ] = new NVPair( "colsREPWIPT0117", "Y" );
        formData[ 53 ] = new NVPair( "colsREPWIPT0118", "Y" );
        formData[ 54 ] = new NVPair( "colsREPWIPT0119", "Y" );
        formData[ 55 ] = new NVPair( "colsREPWIPT0120", "Y" );
        formData[ 56 ] = new NVPair( "colsREPWIPT0121", "Y" );
        formData[ 57 ] = new NVPair( "colsREPWIPT0122", "Y" );
        formData[ 58 ] = new NVPair( "colsREPWIPT0123", "Y" );
        formData[ 59 ] = new NVPair( "colsREPWIPT0124", "Y" );
        formData[ 60 ] = new NVPair( "colsREPWIPT0125", "Y" );
        formData[ 61 ] = new NVPair( "colsREPWIPT0126", "Y" );
        formData[ 62 ] = new NVPair( "colsREPWIPT0127", "Y" );
        formData[ 63 ] = new NVPair( "colsREPWIPT0128", "Y" );

        formData[ 64 ] = new NVPair( "favreplace", "wip_carlos^wipo report" );
        formData[ 65 ] = new NVPair( "favname", "" );
        formData[ 66 ] = new NVPair( "favdesc", "" );
        formData[ 67 ] = new NVPair( "other_users", "" );

        formData[ 68 ] = new NVPair( "typesub", "DROP_CSV" );
        formData[ 69 ] = new NVPair( "subtime", "D" );
        formData[ 70 ] = new NVPair( "submin", "0" );
        formData[ 71 ] = new NVPair( "subweek", "Select weekday" );
        formData[ 72 ] = new NVPair( "subday", "Select day" );
        formData[ 73 ] = new NVPair( "existsub", "IBM NEW^c1018125251150" );
        formData[ 74 ] = new NVPair( "Right", "Select" );
        formData[ 75 ] = new NVPair( "Left", "Remove" );
        formData[ 76 ] = new NVPair( "Sfavdesc_B", "" );
        formData[ 77 ] = new NVPair( "Sfavname_B", "" );
        formData[ 78 ] = new NVPair( "bopn_download", "Download" );

        rsp = conn.Post( WIP_DOWNLOAD, formData );

        return rsp;

    }


    //Added by ChandraSekhar on 5th Aug2004
    /**
     * @param conn HTTPConnection object
     * @return HTTPResponse rsp
     *
     * @throws Exception
     */
    private HTTPResponse requestShipmentStatus( HTTPConnection conn ) throws Exception
    {

        System.out.println( "Submitting HTTP Request for getting Shippment Status " );
        log( "Submitting HTTP Request for getting Shippment Status" );

        HTTPResponse rsp = conn.Get( SHIPMENT_STATUS_LINK );

        /*BufferedReader reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
        String line = null;
        while ( ( line = reader.readLine() ) != null )
        {
            //System.out.println(line);
            log(line);
        }
        */
        //https://www-309.ibm.com/technologyconnect/ordmgt/Download.wss?ftype=shipment&subcon=''&zgpartner=''&customerlist='0000015635'&fromdate=20091113&todate=20091120&inbox=false&reqtagid=
        NVPair[] formData = new NVPair[ 14 ];
        
        formData[ 0 ] = new NVPair( "ftype", "shipment" );
        formData[ 1 ] = new NVPair( "customerlist", m_accountNumber );
        formData[ 2 ] = new NVPair( "subcon", "''" );
        formData[ 3 ] = new NVPair( "zgpartner", "''" );
        formData[ 4 ] = new NVPair( "fromdate", DateUtil.getPreviousDate(7, "yyyyMMdd") );
        formData[ 5 ] = new NVPair( "todate", DateUtil.getCurrentDate("yyyyMMdd") );
        formData[ 6 ] = new NVPair( "inbox", "false" );
        formData[ 7 ] = new NVPair( "reqtagid", "" );
        formData[ 8 ] = new NVPair( "userid", m_username.substring(0, m_username.indexOf("@")+1) );
        formData[ 9 ] = new NVPair( "vendor", "false" );
        formData[ 10 ] = new NVPair( "notification", "false" );
        formData[ 11 ] = new NVPair( "sono", "null" );
        formData[ 12 ] = new NVPair( "pono", "null" );
        formData[ 13 ] = new NVPair( "custpart", "null" );

        rsp = conn.Post( SHIP_DOWNLOAD, formData );
        return rsp;

    }


    /**
     *  Logs out from the IBM Site
     */
    private void logout( HTTPConnection conn ) throws Exception
    {
        try
        {

            System.out.print( "\n Loggin out... " );
            log( "\n Loggin out... " );
            HTTPResponse rsp = conn.Get( GET_URI_LOGOUT );
            System.out.println( "Successfully logged out from IBM Site" );
            log( "Successfully logged out from IBM Site" );
            BufferedReader reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
            String line = null;

            while ( ( line = reader.readLine() ) != null )
            {
                //System.out.println(line);
            }

            conn = null;
            rsp = null;

        }
        catch ( Exception ignore )
        {
            System.out.println( " IBM Adapator thown Failed while logout " );
            throw ignore;
        }
    }

    private void log( String message )
    {

        if ( message == null ) return;

        if ( m_adaptorLogger != null )
        {
            synchronized ( m_adaptorLogger )
            {
                m_adaptorLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}
